package com.dianban.controller;

import com.alibaba.fastjson.JSONObject;
import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.entity.*;
import com.dianban.service.*;
import com.dianban.utils.*;
import com.dianban.weixin.util.WeiXinUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wujh
 * @create 2020/1/10
 */
@Api(value = "ApiUserController", description = "用户控制器")
@RestController
@RequestMapping(value = "${interfacePath}/user/")
public class ApiUserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private ShoproOrderService shoproOrderService;
    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private StoreGuideService storeGuideService;

    @ApiOperation(notes = "login", httpMethod = "POST", value = "用户登录(弃用)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query",dataType = "string"),
    })
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public ResultVo login(String mobile , String password, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isEmpty(mobile)){
            return ResultVo.error(ResultCode.ERROR,"手机号不能为空");
        }
        if(StringUtils.isEmpty(password)){
            return ResultVo.error(ResultCode.ERROR,"密码不能为空");
        }
        User user = userService.findByMobile(mobile);
        if(user == null){
            return ResultVo.error(ResultCode.ERROR,"手机号不存在");
        }
        String passwordMd5 = MD5.parseMD5(MD5.parseMD5(password)+user.getSalt());
        if(!passwordMd5.equals(user.getPassword())){
            return ResultVo.error(ResultCode.ERROR,"密码错误，请重新输入");
        }
        StoreGuide storeGuide = storeGuideService.findByUserId(user.getId());
        if(storeGuide != null){
            user.setIsStoreGuide(1);
        }
        Map<String,Object> resultMap = new HashMap<>();
        String userToken = IdGen.uuid();
        user.setUserToken(userToken);
        String key = RedisConstant.USER_TOKEN_KEY+userToken;
        RedisUtil.set(key,user,3600);
        resultMap.put("user",user);
        return ResultVo.success(resultMap,"成功");
    }

    @ApiOperation(notes = "logout", httpMethod = "GET", value = "用户登出(弃用)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public ResultVo logout(HttpServletRequest request, HttpServletResponse response) {
        UserUtils.logoutUser(request);
        return ResultVo.success("", "操作成功");
    }

    @ApiOperation(notes = "getUser", httpMethod = "GET", value = "获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "门店用户token", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "openid", value = "用户openid", required = true, paramType = "query",dataType = "string"),
    })
    @RequestMapping(value = "getUser",method = RequestMethod.GET)
    public ResultVo getUser(String openid , HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isBlank(openid)){
            return ResultVo.error(ResultCode.ERROR,"用户openid不能为空");
        }
        WxUser wxUser = wxUserService.findByOpenId(openid);
        if(wxUser == null){
            return ResultVo.success("当前用户未绑定手机","当前用户未绑定手机");
        }
        Long userId= wxUser.getUserId();
        User user = userService.findById(userId);
        StoreGuide storeGuide = storeGuideService.findByUserId(userId);
        if(storeGuide != null){
            user.setIsStoreGuide(1);
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("user",user);
        return ResultVo.success(resultMap,"获取成功");
    }

    @ApiOperation(notes = "sendCode", httpMethod = "GET", value = "发送短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "门店用户token", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "mobile", value = "手机号码", required = true, paramType = "query",dataType = "string"),
    })
    @RequestMapping(value = "sendCode",method = RequestMethod.GET)
    public ResultVo sendCode(String mobile , HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isBlank(mobile)){
            return ResultVo.error(ResultCode.ERROR,"手机号码不能为空");
        }
        String code = String.valueOf((int) (Math.random() * 9000 + 1000));
        RedisUtil.set(mobile,code,120);
        //JSONObject smsParam = SmsUtil.getSmsParam(SmsUtil.sendCodeContent,code,"");
        //SmsUtil.sendSms(mobile, "SMScode", "易家科技", smsParam);
        TencentSmsUtils.sendSms("4", mobile, code, "");
        return ResultVo.success("","发送成功");
    }


    @ApiOperation(notes = "bindMobile", httpMethod = "POST", value = "用户绑定手机")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "门店用户token", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "openid", value = "用户openid", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "mobile", value = "手机号码", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query",dataType = "string"),

    })
    @RequestMapping(value = "bindMobile",method = RequestMethod.POST)
    public ResultVo bindPhone(String openid,String mobile , String code,HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(openid)) {
            return ResultVo.error(ResultCode.ERROR, "用户openid不能为空");
        }
        if (StringUtils.isEmpty(mobile)) {
            return ResultVo.error(ResultCode.ERROR, "手机号码不能为空");
        }
        if (StringUtils.isEmpty(code)) {
            return ResultVo.error(ResultCode.ERROR, "验证码不能为空");
        }
        String mobileCode = (String)RedisUtil.get(mobile);
        if(StringUtils.isBlank(mobileCode)){
            return ResultVo.error(ResultCode.ERROR,"验证码已过期，请重新获取");
        }
        if(!mobileCode.equals(code)){
            return ResultVo.error(ResultCode.ERROR,"验证码错误,请重新输入");
        }
        WxUser wxUser = wxUserService.findByOpenId(openid);
        if (wxUser != null) {
            return ResultVo.error(ResultCode.ERROR, "当前用户已绑定手机");
        }
        User user = userService.findByMobile(mobile);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "亲，您还没有注册成为我们的会员，请稍等");
        }
        StoreGuide storeGuide = storeGuideService.findByUserId(user.getId());
        if(storeGuide != null){
            user.setIsStoreGuide(1);
        }
        wxUser = new WxUser();
        wxUser.setUserId(user.getId());
        wxUser.setOpenId(openid);
        wxUserService.insert(wxUser);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("user",user);
        return ResultVo.success(resultMap,"获取成功");
    }

    @ApiOperation(notes = "bindUser", httpMethod = "POST", value = "用户绑定手机")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "门店用户token", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "openid", value = "用户openid", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "userId", value = "手机号码", required = true, paramType = "query",dataType = "string"),

    })
    @RequestMapping(value = "bindUser",method = RequestMethod.POST)
    public ResultVo bindUser(String openid,Long userId) {
        if (StringUtils.isEmpty(openid)) {
            return ResultVo.error(ResultCode.ERROR, "用户openid不能为空");
        }
        if (userId == null) {
            return ResultVo.error(ResultCode.ERROR, "手机号码不能为空");
        }
        WxUser wxUser = wxUserService.findByOpenId(openid);
        if (wxUser != null) {
            return ResultVo.error(ResultCode.ERROR, "当前用户已绑定");
        }
        User user = userService.findById(userId);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "前用户不存在");
        }
        wxUser = new WxUser();
        wxUser.setUserId(userId);
        wxUser.setOpenId(openid);
        wxUserService.insert(wxUser);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("user",user);
        return ResultVo.success(resultMap,"获取成功");
    }

    @ApiOperation(notes = "canBecomeStation", httpMethod = "POST", value = "能否成为站长")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户编号", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "storeId", value = "门店编号", required = true, paramType = "query",dataType = "string"),
    })
    @RequestMapping(value = "canBecomeStation")
    public Map<String,Object> canBecomeStation(Long userId,Long storeId){
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> result  = new HashMap<>();
        result.put("canBecome",userService.canBecomeStation(userId,storeId));
        map.put("success",true);
        map.put("result",result);
        return map;
    }
}
